package com.cryptape.cita_wallet.fragment;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alm.token.ConStant;
import com.alm.token.MyApp;
import com.alm.token.R;
import com.alm.token.apinew.BaseObserver;
import com.alm.token.apinew.RetrofitUtil;
import com.alm.token.ui.activity.BlockWalletLoginActivity;
import com.alm.token.ui.activity.MainActivity;
import com.alm.token.ui.activity.SetLanguageActivity;
import com.alm.token.ui.data.bean.UserData;
import com.alm.token.utils.LogUtil;
import com.alm.token.utils.SpUtil;
import com.alm.token.widget.MQGlideImageLoader4;
import com.cryptape.cita_wallet.activity.AddWalletActivity;
import com.cryptape.cita_wallet.activity.SimpleWebActivity;
import com.cryptape.cita_wallet.activity.WalletManageActivity;
import com.cryptape.cita_wallet.activity.changewallet.ChangeWalletActivity;
import com.cryptape.cita_wallet.constant.ConstantUtil;
import com.cryptape.cita_wallet.constant.url.HttpUrls;
import com.cryptape.cita_wallet.item.Wallet;
import com.cryptape.cita_wallet.service.http.EthRpcService;
import com.cryptape.cita_wallet.util.Blockies;
import com.cryptape.cita_wallet.util.db.DBWalletUtil;
import com.cryptape.cita_wallet.util.db.SharePrefUtil;
import com.cryptape.cita_wallet.util.fingerprint.AuthenticateResultCallback;
import com.cryptape.cita_wallet.util.fingerprint.FingerPrintController;
import com.cryptape.cita_wallet.view.SettingButtonView;
import com.cryptape.cita_wallet.view.dialog.AuthFingerDialog;
import com.cryptape.cita_wallet.view.dialog.SimpleSelectDialog;
import com.cryptape.cita_wallet.view.dialog.ToastSingleButtonDialog;
import com.meiqia.core.MQManager;
import com.meiqia.core.bean.MQMessage;
import com.meiqia.core.callback.OnGetMessageListCallback;
import com.meiqia.core.callback.OnInitCallback;
import com.meiqia.meiqiasdk.imageloader.MQImage;
import com.meiqia.meiqiasdk.util.MQConfig;
import com.meiqia.meiqiasdk.util.MQIntentBuilder;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

;

/**
 * Created by duanyytop on 2018/4/17
 */
public class SettingsFragment extends NBaseFragment {

    private static final int Currency_Code = 10001;
    public static final String TAG = SettingsFragment.class.getName();
    private SettingButtonView mSbvCurrency, sbv_manager_wallet, mSbvSelectLanguage, mSbvFingerPrint, mSbvForums, mSbvSelectEth;
    private RelativeLayout sbv_kefu;
    private TextView tvKefulistnum;
    private TextView walletNameText, walletAddressText;
    private CircleImageView photoImage;
    private RelativeLayout walletLayout;
    private AuthFingerDialog mAuthFingerDialog = null;
    private List<String> ethNodeList = Arrays.asList(ConstantUtil.ETH_NET_MAIN, ConstantUtil.ETH_NET_ROPSTEN_TEST
            , ConstantUtil.ETH_NET_KOVAN_TEST, ConstantUtil.ETH_NET_RINKEBY_TEST);
    private int ethNodeIndex;
    private FingerPrintController mFingerPrintController;
    private TextView tv_version;
    private SettingButtonView sbv_wallet_pay;
    private TextView btn_wallet_pay;
    private UserData.DataBean.UserBean user;
    private MQManager mqManager;

    @Override
    protected int getContentLayout() {
        return R.layout.fragment_settings;
    }

    @Override
    public void initView() {
        mSbvCurrency = (SettingButtonView) findViewById(R.id.sbv_local_coin);
        sbv_manager_wallet = (SettingButtonView) findViewById(R.id.sbv_manager_wallet);
        mSbvSelectLanguage = (SettingButtonView) findViewById(R.id.sbv_select_language);
        mSbvFingerPrint = (SettingButtonView) findViewById(R.id.sbv_fingerprint);
        mSbvForums = (SettingButtonView) findViewById(R.id.sbv_forums);
        mSbvSelectEth = (SettingButtonView) findViewById(R.id.sbv_eth_select);
        walletNameText = (TextView) findViewById(R.id.text_wallet_name);
        walletAddressText = (TextView) findViewById(R.id.text_wallet_address);
        walletLayout = (RelativeLayout) findViewById(R.id.wallet_information_layout);
        photoImage = (CircleImageView) findViewById(R.id.wallet_photo);
        tv_version = (TextView) findViewById(R.id.tv_version);
        sbv_wallet_pay = (SettingButtonView) findViewById(R.id.sbv_wallet_pay);
        btn_wallet_pay = (TextView) findViewById(R.id.btn_wallet_pay);
        sbv_kefu = (RelativeLayout) findViewById(R.id.sbv_kefu);
        tvKefulistnum = (TextView) findViewById(R.id.tv_kefulistnum);
    }

    @Override
    public void initData() {
        Wallet wallet = DBWalletUtil.getCurrentWallet(getContext());
        if (wallet == null) {
            return;
        }
        walletNameText.setText(wallet.name);
        walletAddressText.setText(wallet.address);
        photoImage.setImageBitmap(Blockies.createIcon(wallet.address));

        updateEthNode();

        mFingerPrintController = new FingerPrintController(getActivity());
        mSbvCurrency.setRightText(SharePrefUtil.getString(ConstantUtil.CURRENCY, ConstantUtil.DEFAULT_CURRENCY));
//        if (mFingerPrintController.isSupportFingerprint()) {
//            mSbvFingerPrint.setVisibility(View.VISIBLE);
//            if (SharePrefUtil.getBoolean(ConstantUtil.FINGERPRINT, false)) {
//                mSbvFingerPrint.setSwitchCheck(true);
//            } else {
//                SharePrefUtil.putBoolean(ConstantUtil.FINGERPRINT, false);
//                mSbvFingerPrint.setSwitchCheck(false);
//            }
//        } else
        {
            mSbvFingerPrint.setVisibility(View.GONE);
        }
        String node = SharePrefUtil.getString(ConstantUtil.ETH_NET, ConstantUtil.ETH_MAINNET);
        if (node.contains("_")) node = node.replace("_", " ");
        mSbvSelectEth.setRightText(node);


        try {
            String versionName = getContext().getPackageManager()
                    .getPackageInfo(getContext().getPackageName(), 0).versionName;
            tv_version.setText(String.format("Version V%s", versionName));
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void initAction() {
//        mSbvCurrency.setOnClickListener(() -> {
//            Intent intent = new Intent(getActivity(), CurrencyActivity.class);
//            startActivityForResult(intent, Currency_Code);
//        });
        btn_wallet_pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(SpUtil.getString(MyApp.context, ConStant.TOKEN, ""))
                        && !TextUtils.isEmpty(SpUtil.getString(MyApp.context, ConStant.MEIQIAID, "")) && !SpUtil.getBoolean(MyApp.context, ConStant.NEEDRELOGINANTTIME, false)) {
                    startActivity(new Intent(getContext(), MainActivity.class));
                } else {
                    if (SpUtil.getBoolean(MyApp.context, ConStant.NEEDRELOGINANTTIME, false)) {
                        SpUtil.putBoolean(MyApp.context, ConStant.REMBERPSW, false);
                    }
//                    startActivity(new Intent(getContext(),BlockWalletLoginActivity.class));
                }
                getActivity().finish();
            }
        });
        mSbvFingerPrint.setSwitchCheckedListener(isChecked -> {
            if (isChecked) {
                //setting fingerprint
                if (mFingerPrintController.hasEnrolledFingerprints() && mFingerPrintController.getEnrolledFingerprints().size() > 0) {
                    if (mAuthFingerDialog == null)
                        mAuthFingerDialog = new AuthFingerDialog(getActivity());
                    mAuthFingerDialog.setOnShowListener((dialogInterface) -> {
                        mFingerPrintController.authenticate(authenticateResultCallback);
                    });
                    mAuthFingerDialog.setOnDismissListener((dialog) -> {
                        mFingerPrintController.cancelAuth();
                    });
                    mAuthFingerDialog.show();
                } else {
                    ToastSingleButtonDialog dialog = ToastSingleButtonDialog.getInstance(
                            getActivity(), getResources().getString(R.string.dialog_finger_setting));
                    dialog.setOnCancelClickListener(view -> {
                        FingerPrintController.openFingerPrintSettingPage(getActivity());
                        view.dismiss();
                    });
                }
            } else {
                //close fingerprint
                SharePrefUtil.putBoolean(ConstantUtil.FINGERPRINT, false);
                mSbvFingerPrint.setSwitchCheck(false);
            }
        });
        sbv_manager_wallet.setOnClickListener(() -> {
            if (DBWalletUtil.getAllWallet(getActivity()).size() >= 1) {
                startActivity(new Intent(getActivity(), ChangeWalletActivity.class));
                getActivity().overridePendingTransition(R.anim.wallet_activity_in, 0);
            } else {
                getActivity().startActivity(new Intent(getActivity(), AddWalletActivity.class));
            }
        });
        mSbvSelectLanguage.setOnClickListener(() -> {
            startActivity(new Intent(getContext(), SetLanguageActivity.class));
//
//            ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
//            ClipData mClipData = ClipData.newPlainText("contact", "Nervos-Neuron");
//            if (cm != null) {
//                cm.setPrimaryClip(mClipData);
//                Toast.makeText(getActivity(), R.string.copy_weixin_success, Toast.LENGTH_SHORT).show();
//            }
        });
        mSbvForums.setOnClickListener(() -> {
            SimpleWebActivity.gotoSimpleWeb(getActivity(), HttpUrls.CITAHUB_TALK_URL);
        });
        mSbvSelectEth.setOnClickListener(() -> {
            SimpleSelectDialog dialog = new SimpleSelectDialog(getActivity(), ethNodeList, -1);
            dialog.setMSelected(ethNodeIndex);
            dialog.setOnOkListener((view -> {
                ethNodeIndex = dialog.getMSelected();
                SharePrefUtil.putString(ConstantUtil.ETH_NET, ethNodeList.get(ethNodeIndex));
                dialog.dismiss();
            }));
            dialog.setOnDismissListener(dialogInterface -> {
                EthRpcService.initNodeUrl();
                updateEthNode();
                String node = SharePrefUtil.getString(ConstantUtil.ETH_NET, ConstantUtil.ETH_NET_MAIN);
                if (node.contains("_")) node = node.replace("_", " ");
                mSbvSelectEth.setRightText(node);
                dialog.dismiss();
            });
        });
        walletLayout.setOnClickListener(v -> startActivity(new Intent(getContext(), WalletManageActivity.class)));
//        mSbvSelectLanguage.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                startActivity(new Intent(getContext(), SwitchLanguageActivity.class));
//            }
//        });
        sbv_kefu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initMeiqia();
            }
        });
    }

    private void initMeiqia() {
        MQConfig.isShowClientAvatar = true;
        MQConfig.ui.titleBackgroundResId = R.color.text_99b71269;
        MQConfig.ui.titleTextColorResId = R.color.white;
        MQConfig.ui.backArrowIconResId = R.drawable.arrow_left;
        MQConfig.init(getActivity(), "59699b908f25aaed455f66aef1f92ab2", new OnInitCallback() {
            @Override
            public void onSuccess(String clientId) {
//                Toast.makeText(getActivity(), "init success", Toast.LENGTH_SHORT).show();
                //2.启动对话界面
                LogUtil.e("clientId=" + clientId);
                MQImage.setImageLoader(new MQGlideImageLoader4());
                Wallet mWallet = DBWalletUtil.getCurrentWallet(getActivity());
                HashMap<String, String> clientInfo = new HashMap<>();
                clientInfo.put("name", mWallet.address);
                clientInfo.put("avatar", "" + Uri.parse("android.resource://" + MyApp.getsInstance().getPackageName() + "/" + R.drawable.icon_meiqiankefu1));
//                clientInfo.put("gender", "男");
//                clientInfo.put("技能1", "休刊");

//                HashMap<String, String> updateInfo = new HashMap<>();
//                updateInfo=clientInfo;

                Intent intent = new MQIntentBuilder(getActivity())
                        .setCustomizedId(clientId)
                        .setClientInfo(clientInfo) // 设置顾客信息 PS: 这个接口只会生效一次,如果需要更新顾客信息,需要调用更新接口

//                        .updateClientInfo(updateInfo) // 更新顾客信息 PS: 如果客服在工作台更改了顾客信息，更新接口会覆盖之前的内容
                        .build();
                startActivity(intent);


                /**
                 * 3.启动留言表单界面  startActivity(new Intent(this, MQMessageFormActivity.class));
                 目前是两种模式：
                 (1) 完全对话模式
                 无机器人时：如果当前客服不在线，直接聊天界面输入就是留言，客服上线后能够直接回复，如果客服在线，则进入正常客服对话模式。
                 有机器人时：如果当前客服不在线时，直接聊天界面输入的话，还是由机器人回答，顾客点击留言就会跳转到表单。
                 (2) 单一表单模式
                 不管客服是否在线都会进入表单，顾客提交后，不会有聊天的界面。这种主要用于一些 App 只需要用户反馈，不需要直接回复的形式。
                 */
//                startActivity(new Intent(getActivity(), MQMessageFormActivity.class));
            }

            @Override
            public void onFailure(int code, String message) {
//                Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
            }
        });

        /**
         * 获取当前 Client 的未读消息
         *
         * @param onGetMessageListCallback 回调
         */
        mqManager = MQManager.getInstance(getActivity());
    }

    public void getUnreadMessages() {
        if (mqManager != null)
            mqManager.getUnreadMessages(new OnGetMessageListCallback() {
                @Override
                public void onSuccess(List<MQMessage> list) {
//                    Toast.makeText(getActivity(), "getUnreadMessages success", Toast.LENGTH_SHORT).show();
                    if (tvKefulistnum != null) {
                        tvKefulistnum.setVisibility(list.size() == 0 ? View.GONE : View.VISIBLE);
                        tvKefulistnum.setText(list.size() == 0 ? "" : list.size() + "");
                    }

                }

                @Override
                public void onFailure(int i, String s) {
//                    Toast.makeText(getActivity(), s, Toast.LENGTH_SHORT).show();
                    if (tvKefulistnum != null)
                        tvKefulistnum.setVisibility(View.GONE);
                }
            });
    }

    private void updateEthNode() {
        switch (SharePrefUtil.getString(ConstantUtil.ETH_NET, ConstantUtil.ETH_NET_MAIN)) {
            case ConstantUtil.ETH_NET_MAIN:
            default:
                ethNodeIndex = 0;
                break;
            case ConstantUtil.ETH_NET_ROPSTEN_TEST:
                ethNodeIndex = 1;
                break;
            case ConstantUtil.ETH_NET_KOVAN_TEST:
                ethNodeIndex = 2;
                break;
            case ConstantUtil.ETH_NET_RINKEBY_TEST:
                ethNodeIndex = 3;
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    AuthenticateResultCallback authenticateResultCallback = new AuthenticateResultCallback() {
        @Override
        public void onAuthenticationError(String errorMsg) {
            mSbvFingerPrint.setSwitchCheck(false);
            Toast.makeText(getContext(), errorMsg, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onAuthenticationSucceeded() {
            mSbvFingerPrint.setSwitchCheck(true);
            if (mAuthFingerDialog != null && mAuthFingerDialog.isShowing())
                mAuthFingerDialog.dismiss();
            SharePrefUtil.putBoolean(ConstantUtil.FINGERPRINT, true);
            Toast.makeText(getContext(), getResources().getString(R.string.fingerprint_setting_sucess), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onAuthenticationFailed() {
            mSbvFingerPrint.setSwitchCheck(false);
            Toast.makeText(getContext(), getResources().getString(R.string.fingerprint_setting_failed), Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case Currency_Code:
                    mSbvCurrency.setRightText(SharePrefUtil.getString(ConstantUtil.CURRENCY, "CNY"));
                    break;
            }
        }
    }
}
